import { createRouter, createWebHistory } from "vue-router";
// import type {RouteMeta} from "vue-router"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {
    //   path: "/",
    //   redirect: "/home",
    // },
    {
      path: "/",
      component: () => import("@/pages/home/Index.vue"),
      children: [
        {
          path: "/",
          redirect: "/home",
        },
        {
          path: "/home",
          component: () => import("@/pages/home/one/Index.vue"),
          meta: {
            title: "嗨购首页",
          },
        },
        {
          path: "/classify",
          component: () => import("@/pages/home/classify/Index.vue"),
          meta: {
            title: "嗨购分类页",
          },
        },
        {
          path: "/cart",
          component: () => import("@/pages/home/cart/Index.vue"),
          // meta路由元信息
          meta: {
            requiredLogin: true,
            title: "嗨购购物车页",
          },
        },
        {
          path: "/mine",
          component: () => import("@/pages/home/mine/Index.vue"),
          meta: {
            requiredLogin: true,
            title: "嗨购我的页",
          },
        },
      ],
    },
    {
      path: "/login",
      component: () => import("@/pages/login/Index.vue"),
      meta: {
        title: "嗨购登录页",
      },
    },
    {
      path: "/register",
      component: () => import("@/pages/register/Index.vue"),
      meta: {
        title: "嗨购注册页",
      },
    },
    {
      // path: "/psw/:tel",
      path: "/psw",
      component: () => import("@/pages/psw/Index.vue"),
      meta: {
        title: "设置密码页",
      },
    },
    {
      path: "/detail/:id",
      component: () => import("@/pages/detail/Index.vue"),
      meta: {
        title: "嗨购详情页",
      },
    },
    {
      path: "/:pathMatch(.*)*",
      component: () => import("@/pages/notfound/Index.vue"),
    },
  ],
});

// interface MetaType {
//   title: string;
//   requiredLogin?: boolean;
//   [propname: string]: any;
// }

// 路由全局前置守卫，做路由鉴权
router.beforeEach((to, from, next) => {
  document.title = (to.meta as { title: string }).title || "嗨购";

  // 先判断是否需要登录
  if (to.meta.requiredLogin) {
    // 再判断是否已登录
    if (localStorage.getItem("token")) {
      next();
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
